package com.leen.security.config;

import com.leen.security.UserDetailsServiceImpl;
import com.leen.security.filter.JwtAuthenticationTokenFilter;
import com.leen.security.filter.LogoutLeenSuccessHandler;
import com.leen.security.filter.UnauthorizedHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * spring security安全权限拦截器的配置
 *
 * @author admin
 * @date 2021-05-11
 */
@EnableWebSecurity
//使用@PreAuthorize 在控制器中生效
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    /**
     * 认证失证自定义json处理
     */
    @Autowired
    private UnauthorizedHandler unauthorizedHandler;

    /**
     * spring mvc写的跨域请求filter
     */
    @Autowired
    private CorsFilter  corsFilter;



    @Autowired
    private LogoutLeenSuccessHandler logoutSuccessHandler;


    /**
     * 自定义token拦截器
     */
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    /**
     * 配置要放行的url地址
     * "/admin/login,/common/**"
     */
    @Value(value = "${security.exlude}")
    private  String exludeUrl;



    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[]   exludeUrlArr=new String[0];

        if(StringUtils.isNotBlank(exludeUrl)){
            exludeUrlArr=exludeUrl.split(",");
        }

        //前后端分离，session禁用掉
        http
                // CSRF禁用，因为不使用session
                .csrf().disable()
                // 认证失败（用名或密码错误）
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                //security异常处理

                // 对于登录login 验证码captchaImage 允许匿名访问
                //.antMatchers("/login","/common/**").permitAll()
                .antMatchers(exludeUrlArr).permitAll()
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated().and()
                //原因是因为springSecurty使用X-Frame-Options防止网页被Frame
                .headers().frameOptions().disable();


        //添加自定义拦截器
        //1、 注销用户  (删除redis中的缓存，spring security用户注销掉)
        //注销用户
        http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);

        //2、用户登录jwt 生成存储到redis业务逻辑
       http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //3、CORS跨域请求放行
        http.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);

        //注销这前，允许跨域访问
        http.addFilterBefore(corsFilter, LogoutFilter.class);

    }

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }


    /**
     * 用户登录和权限分配实现流程
     */
    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;


    /**
     * 设定自定义用户登录权限认证的代码
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceImpl);
    }


    /**
     * 密码使用  BCrypt加密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


}
